import { Component } from 'react';
import classnames from 'classnames';
import { withRouter } from 'react-router';
class SignupForm extends Component {
  constructor () {
    super();
    this.state = {
      userName: '',
      email: '',
      password: '',
      passwordConfirmation: '',
      errors: {},
      isLoading: false
    }
  }

  onChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value,
    })
  }
  onSubmit = (e) => {
    e.preventDefault();
    console.log(this.state);
    // 1需要在父组件内传递history
    this.props.history.push('/');
    // 2使用withRouter则不需要在父组件传递history
    this.props.signupActions.userSignupRequest(this.state).then(
      () => {
        this.props.history.push('/');
      },
      ({response}) => {
        this.setState({
          errors: response.data,
          isLoading: false
        })
      }
    );
  }
  render () {
    const { errors, isLoading } = this.state;
    return (
      <form onSubmit={ this.onSubmit }>
        SignupForm
        <h1>Join our community</h1>
        <div className="form-group">
          <label className="contorl-label">UserName</label>
          <input
            type="text"
            name="userName"
            value={this.state.userName}
            onChange={this.onChange}
          />
          { errors.userName && <span className="form-text text-muted">{errors.userName}</span>}
        </div>
        <div className="form-group">
          <label className="contorl-label">Email</label>
          <input
            type="email"
            name="email"
            value={this.state.email}
            onChange={this.onChange}
          />
          { errors.email && <span className="form-text text-muted">{errors.email}</span>}
        </div>
        <div className="form-group">
          <label className="contorl-label">Password</label>
          <input
            type="password"
            name="password"
            value={this.state.password}
            onChange={this.onChange}
          />
          { errors.password && <span className="form-text text-muted">{errors.password}</span>}
        </div>
        <div className="form-group">
          <label className="contorl-label">PasswordConfirmation</label>
          <input
            type="password"
            name="passwordConfirmation"
            value={this.state.passwordConfirmation}
            onChange={this.onChange}
          />
          { errors.passwordConfirmation && <span className="form-text text-muted">{errors.passwordConfirmation}</span>}
        </div>
        <div className="from-group">
          <button className="btn btn-primary btn-lg">注册</button>
        </div>
      </form>
    )
  }
}

export default withRouter(SignupForm);